<template>
  <div class="my-orders-container">
    <div class="page-header">
      <h1>我的订单</h1>
      <p>管理您的购买记录</p>
    </div>

    <!-- 订单状态筛选 -->
    <div class="order-tabs">
      <el-card>
        <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
          <el-tab-pane label="全部订单" name="ALL" />
          <el-tab-pane label="待付款" name="PENDING_PAYMENT" />
          <el-tab-pane label="待发货" name="PENDING_SHIPMENT" />
          <el-tab-pane label="待收货" name="SHIPPED" />
          <el-tab-pane label="已完成" name="COMPLETED" />
          <el-tab-pane label="已取消" name="CANCELLED" />
        </el-tabs>
      </el-card>
    </div>

    <!-- 订单列表 -->
    <div class="orders-list">
      <div v-loading="loading">
        <div 
          v-for="order in orders"
          :key="order.id"
          class="order-item"
        >
          <el-card>
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.orderNumber }}</span>
                <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.status)" size="large">
                  {{ getStatusText(order.status) }}
                </el-tag>
              </div>
            </div>

            <!-- 订单商品 -->
            <div class="order-products">
              <div 
                v-for="item in order.items"
                :key="item.id"
                class="product-item"
              >
                <el-image
                  :src="item.product.image || '/default-product.jpg'"
                  fit="cover"
                  class="product-image"
                  @click="goToProduct(item.product.id)"
                />
                <div class="product-info">
                  <h4 class="product-name" @click="goToProduct(item.product.id)">
                    {{ item.product.name }}
                  </h4>
                  <p class="product-specs" v-if="item.specs">
                    <el-tag 
                      v-for="(value, key) in item.specs"
                      :key="key"
                      size="small"
                      type="info"
                    >
                      {{ key }}: {{ value }}
                    </el-tag>
                  </p>
                </div>
                <div class="product-price">
                  <span>¥{{ item.price }}</span>
                  <span class="quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>

            <!-- 订单金额 -->
            <div class="order-amount">
              <div class="amount-details">
                <div class="amount-item">
                  <span>商品金额：</span>
                  <span>¥{{ order.productAmount }}</span>
                </div>
                <div class="amount-item" v-if="order.shippingFee > 0">
                  <span>运费：</span>
                  <span>¥{{ order.shippingFee }}</span>
                </div>
                <div class="amount-item" v-if="order.discountAmount > 0">
                  <span>优惠金额：</span>
                  <span class="discount">-¥{{ order.discountAmount }}</span>
                </div>
                <div class="amount-item total">
                  <span>实付金额：</span>
                  <span class="total-amount">¥{{ order.totalAmount }}</span>
                </div>
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <el-button 
                v-if="order.status === 'PENDING_PAYMENT'"
                type="primary"
                @click="payOrder(order)"
              >
                立即付款
              </el-button>
              <el-button 
                v-if="order.status === 'SHIPPED'"
                type="success"
                @click="confirmReceive(order)"
              >
                确认收货
              </el-button>
              <el-button 
                v-if="order.status === 'COMPLETED'"
                type="default"
                @click="reviewOrder(order)"
              >
                评价
              </el-button>
              <el-button 
                v-if="['PENDING_PAYMENT', 'PENDING_SHIPMENT'].includes(order.status)"
                type="danger"
                @click="cancelOrder(order)"
              >
                取消订单
              </el-button>
              <el-button 
                type="default"
                @click="viewOrderDetail(order)"
              >
                查看详情
              </el-button>
            </div>
          </el-card>
        </div>

        <div v-if="orders.length === 0 && !loading" class="no-orders">
          <el-empty description="暂无订单记录">
            <el-button type="primary" @click="goToMall">去购物</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadOrders(true)"
          @current-change="loadOrders(false)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getMyOrders,
  payOrder as apiPayOrder,
  cancelOrder as apiCancelOrder,
  confirmReceive as apiConfirmReceive
} from '@/api/mall'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const orders = ref([])
const total = ref(0)
const activeStatus = ref('ALL')

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10
})

// 获取订单列表
const loadOrders = async (reset = false) => {
  if (reset) {
    pagination.page = 1
  }
  
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      status: activeStatus.value === 'ALL' ? undefined : activeStatus.value
    }
    
    const response = await getMyOrders(params)
    if (response.code === 200) {
      orders.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error('获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 状态切换
const handleStatusChange = (status) => {
  activeStatus.value = status
  loadOrders(true)
}

// 支付订单
const payOrder = async (order) => {
  try {
    await ElMessageBox.confirm(`确认支付订单 ${order.orderNumber}？`, '确认支付', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    // 这里应该跳转到支付页面或调用支付接口
    router.push({
      path: '/mall/payment',
      query: { orderId: order.id }
    })
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error('支付失败')
    }
  }
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(`确认取消订单 ${order.orderNumber}？`, '确认取消', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await apiCancelOrder(order.id)
    ElMessage.success('订单已取消')
    loadOrders(false)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 确认收货
const confirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm(`确认收到订单 ${order.orderNumber} 的商品？`, '确认收货', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await apiConfirmReceive(order.id)
    ElMessage.success('确认收货成功')
    loadOrders(false)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 评价订单
const reviewOrder = (order) => {
  router.push({
    path: '/mall/review',
    query: { orderId: order.id }
  })
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push(`/mall/order/${order.id}`)
}

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/mall/product/${productId}`)
}

// 跳转到商城
const goToMall = () => {
  router.push('/mall')
}

// 工具函数
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

const getStatusType = (status) => {
  const typeMap = {
    'PENDING_PAYMENT': 'warning',
    'PENDING_SHIPMENT': 'info',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PENDING_PAYMENT': '待付款',
    'PENDING_SHIPMENT': '待发货',
    'SHIPPED': '待收货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || status
}

// 页面加载
onMounted(() => {
  loadOrders(true)
})
</script>

<style lang="scss" scoped>
.my-orders-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    font-size: 32px;
    color: #303133;
    margin: 0 0 10px 0;
  }
  
  p {
    color: #606266;
    font-size: 16px;
    margin: 0;
  }
}

.order-tabs {
  margin-bottom: 20px;
}

.orders-list {
  max-width: 1200px;
  margin: 0 auto;
  
  .order-item {
    margin-bottom: 20px;
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 16px;
      
      .order-info {
        display: flex;
        gap: 20px;
        
        .order-number {
          font-weight: 500;
          color: #303133;
        }
        
        .order-time {
          color: #606266;
          font-size: 14px;
        }
      }
    }
    
    .order-products {
      margin-bottom: 16px;
      
      .product-item {
        display: flex;
        gap: 12px;
        padding: 12px 0;
        border-bottom: 1px solid #f8f9fa;
        
        &:last-child {
          border-bottom: none;
        }
        
        .product-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          cursor: pointer;
        }
        
        .product-info {
          flex: 1;
          
          .product-name {
            margin: 0 0 8px 0;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            color: #409eff;
            
            &:hover {
              text-decoration: underline;
            }
          }
          
          .product-specs {
            margin: 0;
            
            .el-tag {
              margin-right: 4px;
            }
          }
        }
        
        .product-price {
          text-align: right;
          
          span {
            display: block;
            color: #e6a23c;
            font-weight: bold;
          }
          
          .quantity {
            color: #606266;
            font-size: 14px;
            font-weight: normal;
          }
        }
      }
    }
    
    .order-amount {
      margin-bottom: 16px;
      
      .amount-details {
        text-align: right;
        
        .amount-item {
          margin: 4px 0;
          
          .discount {
            color: #67c23a;
          }
          
          &.total {
            font-size: 16px;
            font-weight: bold;
            
            .total-amount {
              color: #e6a23c;
              font-size: 18px;
            }
          }
        }
      }
    }
    
    .order-actions {
      text-align: right;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      
      .el-button {
        margin-left: 8px;
      }
    }
  }
}

.no-orders {
  text-align: center;
  padding: 60px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .my-orders-container {
    padding: 10px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    
    .order-info {
      flex-direction: column;
      gap: 4px;
    }
  }
  
  .product-item {
    flex-direction: column;
    
    .product-price {
      text-align: left;
      
      span {
        display: inline;
        margin-right: 10px;
      }
    }
  }
  
  .order-actions {
    text-align: left;
    
    .el-button {
      margin: 4px 8px 4px 0;
    }
  }
}
</style>
